package com.example.canvasdemo.ui

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.canvasdemo.LoginActivity
import com.example.canvasdemo.R
import com.example.canvasdemo.model.ChatMessage
import com.example.canvasdemo.model.Room
import com.example.canvasdemo.model.SendMessageRequest
import com.example.canvasdemo.model.UserModel
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RoomDetailActivity : AppCompatActivity() {

    private lateinit var rvChatMessages: RecyclerView
    private lateinit var etMessage: EditText
    private lateinit var btnSendMessage: Button
    private lateinit var btnRefreshMessages: Button
    private lateinit var btnBecomeDrawer: Button
    private lateinit var btnBecomeGuesser: Button
    private val chatMessages = mutableListOf<ChatMessage>()
    private lateinit var chatAdapter: ChatMessageAdapter

    private val apiService = RetrofitClient.instance.create(ApiService::class.java)
    private var roomId: Long = 0
    private var userId: Long = 0
    private var userName: String = "Guest"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room_detail)

        rvChatMessages = findViewById(R.id.rvChatMessages)
        etMessage = findViewById(R.id.etMessage)
        btnSendMessage = findViewById(R.id.btnSendMessage)
        btnRefreshMessages = findViewById(R.id.btnRefreshMessages)
        btnBecomeDrawer = findViewById(R.id.btnBecomeDrawer)
        btnBecomeGuesser = findViewById(R.id.btnBecomeGuesser)

        roomId = intent.getLongExtra("room_id", 0L)
        if (roomId == 0L) {
            Log.e("RoomDetailActivity", "Invalid roomId: $roomId")
            Toast.makeText(this, "无效的房间ID", Toast.LENGTH_SHORT).show()
            return
        }

        // 获取用户 ID
        userId = getLoggedInUserId()
        if (userId <= 0) {
            Log.e("RoomDetailActivity", "Invalid userId: $userId")
            Toast.makeText(this, "无效的用户ID，请重新登录", Toast.LENGTH_SHORT).show()
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
            return
        }

        // 获取用户信息
        getUserInfo()

        // 设置 RecyclerView
        chatAdapter = ChatMessageAdapter(chatMessages)
        rvChatMessages.layoutManager = LinearLayoutManager(this)
        rvChatMessages.adapter = chatAdapter

        // 发送消息
        btnSendMessage.setOnClickListener {
            val message = etMessage.text.toString().trim()
            if (message.isBlank()) {
                Log.e("SendMessage", "Message content is empty")
                Toast.makeText(this, "消息内容不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            sendMessage(message)
        }

        // 点击刷新按钮获取消息
        btnRefreshMessages.setOnClickListener {
            getMessages()
        }

        // 初始获取消息
        getMessages()

        // 加入房间时，检查房间人数并设置按钮可见性
        checkRoomStatusAndShowRoleButtons()

        // 设置“成为画家”按钮的点击事件
        btnBecomeDrawer.setOnClickListener {
            val roomId: Long = roomId
            val userId: Long = userId
            val userName: String = userName
            val intent = Intent(this@RoomDetailActivity, DrawActivity::class.java)
            intent.putExtra("room_id", roomId)
            intent.putExtra("userId", userId)
            intent.putExtra("userName", userName)
            startActivity(intent)
        }

        // 设置“成为猜词者”按钮的点击事件
        btnBecomeGuesser.setOnClickListener {
            val roomId: Long = roomId
            val userId: Long = userId
            val userName: String = userName
            val intent = Intent(this@RoomDetailActivity, GuessWordActivity::class.java)
            intent.putExtra("room_id", roomId)
            intent.putExtra("userId", userId)
            intent.putExtra("userName", userName)
            startActivity(intent)
        }
    }

    private fun getLoggedInUserId(): Long {
        val sharedPrefs: SharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE)
        return sharedPrefs.getLong("userId", 0)
    }

    private fun getUserInfo() {
        apiService.getUserById(userId).enqueue(object : Callback<UserModel> {
            override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
                if (response.isSuccessful) {
                    val user = response.body()
                    user?.let {
                        userName = it.username
                        // 更新 UI（如果需要显示用户名，可以在此处更新）
                        Log.d("RoomDetailActivity", "用户名: $userName")
                    }
                } else {
                    Toast.makeText(this@RoomDetailActivity, "获取用户信息失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<UserModel>, t: Throwable) {
                Toast.makeText(this@RoomDetailActivity, "获取用户信息失败: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun sendMessage(message: String) {
        val userId = getLoggedInUserId()
        val intRoomId = roomId.toInt()
        val intUserId = userId.toInt()

        if (userId <= 0) {
            Toast.makeText(this, "无效的用户ID，请重新登录", Toast.LENGTH_SHORT).show()
            return
        }

        val sendMessageRequest = SendMessageRequest(intRoomId, intUserId, message)

        apiService.sendMessage(intRoomId, sendMessageRequest)
            .enqueue(object : Callback<ChatMessage> {
                override fun onResponse(call: Call<ChatMessage>, response: Response<ChatMessage>) {
                    if (response.isSuccessful) {
                        response.body()?.let {
                            chatMessages.add(it)
                            chatAdapter.notifyItemInserted(chatMessages.size - 1)
                            rvChatMessages.scrollToPosition(chatMessages.size - 1)
                            etMessage.text.clear()
                        }
                    } else {
                        Toast.makeText(this@RoomDetailActivity, "消息发送失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<ChatMessage>, t: Throwable) {
                    Toast.makeText(this@RoomDetailActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun getMessages() {
        apiService.getMessages(roomId)
            .enqueue(object : Callback<List<ChatMessage>> {
                override fun onResponse(call: Call<List<ChatMessage>>, response: Response<List<ChatMessage>>) {
                    if (response.isSuccessful) {
                        response.body()?.let { messages ->
                            chatMessages.clear()
                            if (messages.isEmpty()) {
                                Toast.makeText(this@RoomDetailActivity, "房间内暂无聊天记录", Toast.LENGTH_SHORT).show()
                            } else {
                                chatMessages.addAll(messages)
                                chatAdapter.notifyDataSetChanged()
                            }
                        }
                    } else {
                        Toast.makeText(this@RoomDetailActivity, "获取聊天记录失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<List<ChatMessage>>, t: Throwable) {
                    Toast.makeText(this@RoomDetailActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun checkRoomStatusAndShowRoleButtons() {
        apiService.getRoomStatus(roomId).enqueue(object : Callback<Room> {
            override fun onResponse(call: Call<Room>, response: Response<Room>) {
                if (response.isSuccessful) {
                    val room = response.body()
                    val playerCount = room?.playerCount ?: 0  // 获取当前玩家数量（使用playerCount）
                    // 检查玩家数是否大于等于 2
                    if (playerCount < 2) {
                        Toast.makeText(this@RoomDetailActivity, "房间人数不够，无法开始游戏", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Toast.makeText(this@RoomDetailActivity, "获取房间信息失败", Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<Room>, t: Throwable) {
                Toast.makeText(this@RoomDetailActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }
}
